import { getDeviceProfiles } from '/@/api/thingsborad/profile/deviceProfile/deviceProfile';
import { getAssetProfileTableList } from '/@/api/thingsborad/profile/assetProfile/assetProfile';
import { entityTableParams } from '/@/api/thingsborad/entity/model/entityModel';
import { getEntityDeviceList } from '/@/api/thingsborad/entity/entity';

const params = {
  page: 0,
  pageSize: 10,
  sortOrder: 'DESC',
  sortProperty: 'createdTime',
};

// 定义一个函数来获取 deviceId，内部缓存结果
export const getDeviceProfilesId = (() => {
  let cachedId; // 缓存的 deviceId
  let isPending = false; // 是否正在获取中（避免重复请求）

  return async () => {
    if (cachedId !== null && cachedId !== undefined) {
      return cachedId; // 直接返回缓存值
    }

    if (!isPending) {
      isPending = true;
      try {
        const result = await getDeviceProfiles(params);
        if (result.data && result.data.length > 0) {
          cachedId = result.data[0].id.id;
        } else {
          cachedId = null; // 未找到时标记为 null
        }
      } catch (error) {
        console.error('获取设备配置失败:', error);
        cachedId = null;
      } finally {
        isPending = false;
      }
    }

    return cachedId;
  };
})();

// 获取资产配置ID
export const getAssetProfileId = (() => {
  let cachedAssetId; // 缓存的 assetId
  let isPending = false; // 是否正在获取中

  return async () => {
    if (cachedAssetId !== null && cachedAssetId !== undefined) {
      return cachedAssetId; // 直接返回缓存值
    }

    if (!isPending) {
      isPending = true;
      try {
        const result = await getAssetProfileTableList(params);
        if (result.data && result.data.length > 0) {
          cachedAssetId = result.data[0].id.id; // 根据实际数据结构调整路径
        } else {
          cachedAssetId = null;
        }
      } catch (error) {
        console.error('获取资产配置失败:', error);
        cachedAssetId = null;
      } finally {
        isPending = false;
      }
    }

    return cachedAssetId;
  };
})();

//获取全部设备
export const getAllDevices = async (
  searchParams?: Omit<
    entityTableParams & { deviceId?: string; deviceProfileId?: string; active?: boolean },
    'page' | 'pageSize'
  >,
) => {
  const pageSize = 10; // 后端允许的最大分页大小
  let page = 0;
  const allData: any[] = [];

  while (true) {
    const params: entityTableParams & {
      deviceId?: string;
      deviceProfileId?: string;
      active?: boolean;
    } = {
      page,
      pageSize,
      ...searchParams, // 合并其他参数
    };

    const response = await getEntityDeviceList(params);
    const currentData = response.data;

    allData.push(...currentData);

    // 当前页数据不足一页，说明是最后一页
    if (currentData.length < pageSize) {
      break;
    }

    page++;
  }

  return allData;
};

